package com.shanxia.im.sdk.client;

import com.shanxia.im.sdk.client.model.Intent;

/**
 * 与服务端连接服务
 */
public class CIMPushService {

	private final CIMConnectorManager manager;

	private static CIMPushService service;

	public static CIMPushService getInstance() {
		if (service == null) {
			service = new CIMPushService();
		}
		return service;
	}

	public CIMPushService() {
		manager = CIMConnectorManager.getManager();
	}

	public void onStartCommand(Intent intent) {

		String action = intent == null ? CIMPushManager.ACTION_ACTIVATE_PUSH_SERVICE : intent.getAction();

		if (CIMPushManager.ACTION_CREATE_CIM_CONNECTION.equals(action)) {
			String host = CIMCacheManager.getInstance().getString(CIMCacheManager.KEY_CIM_SERVER_HOST);
			int port = CIMCacheManager.getInstance().getInt(CIMCacheManager.KEY_CIM_SERVER_PORT);
			manager.connect(host, port);
		}

		if (CIMPushManager.ACTION_SEND_REQUEST_BODY.equals(action)) {
			manager.send(intent.getProtocolDataBase());
		}

		if (CIMPushManager.ACTION_CLOSE_CIM_CONNECTION.equals(action)) {
			manager.closeSession();
		}

		if (CIMPushManager.ACTION_DESTROY.equals(action)) {
			manager.destroy();
		}

		if (CIMPushManager.ACTION_ACTIVATE_PUSH_SERVICE.equals(action) && !manager.isConnected()) {

			String host = CIMCacheManager.getInstance().getString(CIMCacheManager.KEY_CIM_SERVER_HOST);
			int port = CIMCacheManager.getInstance().getInt(CIMCacheManager.KEY_CIM_SERVER_PORT);
			manager.connect(host, port);
		}
	}

}
